<template>
	<view class="container">
		<view class="content-wrap">
			<image class="decorate" src="@/static/new/blessingPoints/calendar-bg2.png"></image>
			<view class="title">
				<view class="left">
					<image src="@/static/new/blessingPoints/calendar-icon.png"></image>
					<text class="has-sign">本月已签到{{ signDays }}天</text>
					<text class="miss-sign">漏签到{{ missDays }}天</text>
				</view>
				<text class="right" @tap="sign" :style="{ backgroundColor: isSign ? '#999' : '#24c789', boxShadow: isSign ? '0rpx 6rpx 14rpx 0rpx #ccc' : '0rpx 6rpx 14rpx 0rpx #B8FBE1', }">签到</text>
			</view>
			<qian-dao :list="list" :date="date" :time_key="time_key" :ruleJson="ruleJson" @day_change="day_change_fun" @date_change="date_change_fun"></qian-dao>
		</view>
	</view>
</template>

<script>
	// 签到
	import dayjs from 'dayjs'
	import QianDao from "./components/qian-dao.vue";
	import { $scoreSignRecord, $scoreSignCheck, $scoreRecordSave, $scoreCoupon } from '@/http/apiManager.js'
	import storageManage from '@/util/storageManage.js'
	import appConfig from '@/config/appConfig.js'
	
	// 签到并发
	let isClick = false
	
	export default {
		// 组件
		components: {
			// 签到
			QianDao,
		},
		data() {
			return {
				signScoreRule: {},	// 签到规则
				// 签到的ruleId
				ruleId: '',
				// 签到获取的福分数量
				ruleValue: '',
				ruleJson: {},
				// 当天是否签到
				isSign: false,	// 默认未签到
				userId: storageManage.userId(),
				// 当前的日期
				date: dayjs().format('YYYY-MM'),

				// 存放时间的key值
				time_key: "time",
				list: [],
				// 已经签到的数据列表
				// list: ["2024-03-11", "2024-03-12", "2024-03-13", ],
				
				// // 存放时间的key值
				// time_key: "time",
				// // 已经签到的数据列表
				// list: [{
				// 	time: "2020-05-10",
				// }, {
				// 	time: "03-15",
				// }, {
				// 	time: "20",
				// }, {
				// 	time: "31"
				// }],
			}
		},
		computed: {
			// 签到的天数
			signDays(){
				return this.list.length
			},
			// 漏签的天数
			missDays(){
				const currntYearMonth = dayjs().format('YYYY-MM')	
				const day = dayjs().format('D')
				if(this.date === currntYearMonth){
					return day - this.list.length
				}else{
					return dayjs(this.date).daysInMonth() - this.list.length
				}
			}
		},
		created(){
			// 漏签以及签到
			// this.missAndSignDays()
		},
		async onLoad({ rule }) {
			this.signScoreRule = JSON.parse(decodeURI(rule))
			this.ruleId = this.signScoreRule.scoreRuleId
			this.ruleValue = this.signScoreRule.ruleValue
			this.ruleJson = JSON.parse(this.signScoreRule.ruleJson.trim())
			// 请求签到记录
			await this.signRecord(dayjs().format('YYYY-MM-DD'))
			// 当天是否签到
			await this.todayIsSign()
			uni.hideLoading()
		},
		// 方法
		methods: {
			// 点击天
			day_change_fun(day) {

				// 存放时间的key值
				let time_key = this.time_key;

				// 如果没有签到（可以补签，需要补签的可以这么写）
				if (!day.click) {
					if (time_key) {
						let obj = {};
						obj[time_key] = day.nyr;
						this.list.push(obj);
					} else {
						this.list.push(day.nyr);
					}
				}

				// 如果今天没有签到(只签到今天的，如果只需要签到今天的可以这么写)
				// if (!day.click && day.type == "today") {
				// 	if (time_key) {
				// 		let obj = {};
				// 		obj[time_key] = day.nyr;
				// 		this.list.push(obj);
				// 	} else {
				// 		this.list.push(day.nyr);
				// 	}
				// }
			},
			// 日期改变时触发
			date_change_fun(date) {
				// 更新日期
				this.date = date;

				// 清空已经签到的列表
				// this.list = [];

				// 根据日期获取已经签到的列表然后赋值
				// 存放时间的key值
				// let time_key = this.time_key;
				// if (time_key) {
				// 	this.list.push({
				// 		time: "01"
				// 	});
				// } else {
				// 	this.list.push("01");
				// }
				// 请求签到记录
				this.signRecord(dayjs(date).format('YYYY-MM-[01]'))
			},
			// 自定义导航栏，返回上一级
			back(){
				uni.navigateBack()
			},
			// 请求签到记录
			signRecord(time){
				return new Promise((resolve,reject) => {
					$scoreSignRecord({
						ruleId: this.ruleId,
						time,
					}).then(res => {
						this.list = res.bizData.map(item => {
							item.time = dayjs(item.createdAt).format('YYYY-MM-DD')
							return item
						})
						resolve()
					})
				})
			},
			// 当天是否签到校验
			todayIsSign(){
				return new Promise((reslove,reject) => {
					if(dayjs().isSame(storageManage.isSign(),'days')){
						this.isSign = true	// 已签到
						return reslove(this.isSign)
					}
					$scoreSignCheck({
						infoId: this.ruleId
					}).then(({ bizData }) => {
						if(bizData.flag === 'true'){
							this.isSign = false	// 未签到
						}else{
							this.isSign = true	// 已签到
						}
						// 本地缓存当天签到 记录 签到日期
						if(this.isSign){
							storageManage.isSign(dayjs().format('YYYY-MM-DD'))
						}
						reslove(this.isSign)
					}).catch(error => {
						reslove()
					})
				})
			},
			
			// 签到
			sign(){
				getApp().preventActive(async ()=>{
					if(isClick) return
					isClick = true
					uni.showLoading({
						title: '加载中...',
						mask: true
					})
					try{
						const res = await this.todayIsSign()
						if(res){
							uni.hideLoading()
							this.$infoBox.toast('今日已签到！')
							return
						}
						await $scoreRecordSave({ ruleId: this.ruleId })
						this.$infoBox.toast('签到成功！')
						// 刷新签到按钮状态
						this.isSign = true
						// 签到成功后缓存签到日期
						storageManage.isSign(dayjs().format('YYYY-MM-DD'))
						// 请求签到记录
						this.signRecord(dayjs().format('YYYY-MM-DD'))
						// 页面通讯福分页面 数据更新
						uni.$emit('SCORE_INIT_PAGE')
					}finally{
						isClick = false
					}
				})
			}
		},
	}
</script>

<style lang="less">
	.container{
		width: 100%;
		min-height: 100vh;
		position: relative;
		background-image: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/68e45da5-594d-417f-a974-445f485c50c5.png');
		background-color: #D3F4E7;
		background-size: 100% 384rpx;
		background-position: 0 0;
		background-repeat: no-repeat;
		overflow: hidden;
		.content-wrap{
			margin: 330rpx 24rpx 24rpx;
			// padding: 60rpx 20rpx;
			border-radius: 25rpx;
			position: relative;
			background-color: #fff;
			overflow: visible;
			.decorate{
				width: calc(100% - 12rpx);
				height: 158rpx;
				position: absolute;
				top: -16rpx;
				left: 6rpx;
				z-index: 1;
			}
			.title{
				position: relative;
				z-index: 1;
				padding: 60rpx 20rpx 0 20rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 32rpx;
				.left{
					// position: relative;
					display: flex;
					flex-shrink: 0;
					align-items: flex-end;
					image{
						width: 54rpx;
						height: 60rpx;
						position: relative;
					}
					.has-sign{
						padding: 10rpx 24rpx 10rpx 60rpx;
						font-size: 26rpx;
						color: #FFFFFF;
						background: #FFB138;
						border-radius: 10rpx;
						position: relative;
						left: -60rpx;
						z-index: -1;
					}
					.miss-sign{
						font-size: 26rpx;
						color: #333333;
						background: linear-gradient( 270deg, rgba(36,199,137,0) 0%, rgba(36,199,137,0.4) 100%);
						padding: 10rpx 24rpx 10rpx 60rpx;
						position: relative;
						left: -100rpx;
						z-index: -2;
					}
				}
				
				.right{
					flex-shrink: 0;
					background: #24C789;
					box-shadow: 0rpx 6rpx 14rpx 0rpx #B8FBE1;
					border-radius: 38rpx;
					padding: 18rpx 55rpx;
					font-weight: 500;
					font-size: 32rpx;
					color: #FFFFFF;
					position: absolute;
					right: 20rpx;
				}
			}
		}
	}
</style>